import axios from 'axios';
// import qs from 'qs';
import { ElNotification } from 'element-plus';
import tool from './tool'
import router from '../router'

axios.defaults.baseURL = ''

axios.defaults.timeout = 10000000

// HTTP request 拦截器
axios.interceptors.request.use(
	(config) => {
		// config.headers['Authorization'] = "yyk-Auth"
		let token = tool.data.get("TOKEN");
		if(token){
			config.headers['token'] = token
		}

		// config.headers['Content-Type'] = "application/x-www-form-urlencoded"
		// config.data = qs.stringify(config.data)
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// HTTP response 拦截器
axios.interceptors.response.use(
	(response) => {
		console.log('api',response.config.url)
		console.log('return',response.data)
		if(response.data.code!="200"){
			// ElNotification.error({
			// 	title: response.data.msg,
			// 	message: JSON.stringify(response.data)
			// });
		}

		if(response.data.code=="403"){
			router.replace({path: '/login'});
		}


		return response;
	},
	(error) => {
		if(error.response.status == 404){
			ElNotification.error({
				title: '请求错误',
				message: "Status:404，正在请求不存在的服务器记录！"
			});
		}
		if(error.response.status == 500){
			ElNotification.error({
				title: '请求错误',
				message: "Status:500，服务器发生错误！"
			});
		}

		return Promise.reject(error.response);
	}
);

var http = {

	/** get 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} params
	 */
	get: function(url, params={}) {
		return new Promise((resolve, reject) => {
			let user = tool.data.get("user")
			if(user){
					params.token = user.token
			}
			axios.get(url, {
					params: params
				})
				.then((response) => {
					resolve(response.data);
				})
				.catch((error) => {
					reject(error);
				});
		})
	},
	xz: function(url, params={}) {
		return new Promise((resolve, reject) => {
			axios.get(url, {
				params: params,
				responseType: 'blob'
			})
				.then((response) => {
					resolve(response.data);
				})
				.catch((error) => {
					reject(error);
				});
		})
	},

	/** post 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} params
	 */
	post: function(url, params={}) {
		return new Promise((resolve, reject) => {
			let user = tool.data.get("user")
			if(user){
				params.token = user.token
			}
			axios.post(url, params)
				.then((response) => {
					resolve(response.data);
				})
				.catch((error) => {
					reject(error);
				});
		})
	}
}

export default http;
